<?php
namespace Icsoc\SecurityBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class RoleTransformationCommand
 * @package Icsoc\SecurityBundle\Command
 */
class RoleTransformationCommand extends ContainerAwareCommand
{
    /**老权限==>新权限
     * @var array
     */
    private $relation = array(
        'account'=>'icsoc_security_setting',
        'role'=>'icsoc_security_role_info',
        'agents'=>'icsoc_agent_index',
        'rule'=>'icsoc_rules_list',
        'laterule'=>'icsoc_rules_list',
        'phones'=>'icsoc_phone_manage_index',
        'ivr'=>'icsoc_ivr_list',
        'sounds'=>'icsoc_sound_index',
        'groups'=>'icsoc_queue_index',
        'agqu'=>'icsoc_queue_agqu_index', //技能组快捷分配；
        'blacklist'=>'icsoc_namelist_black_index',
        'records'=>'icsoc_recording_list',
        'voice'=>'icsoc_recording_message_lsit',
        'msystem'=>'icsoc_monitor_system_monitor',
        'magent_'=>'icsoc_monitor_agent_monitor',
        'magent_conf'=>'icsoc_monitor_call_center_monitor',
        'magent_config'=>'icsoc_monitor_conf_monitor',
        'rincoming'=>'icsoc_report_callin',
        'rout'=>'icsoc_report_callout',
        'calldetail'=>'icsoc_report_call',
        'agentdetail'=>'icsoc_report_agentstate',
        'rconference'=>'icsoc_report_conference',
        'rmonitor'=>'icsoc_report_monitor',
        'sms'=>'icsoc_report_sms',
        'rlost'=>'icsoc_report_lost',
        'inallot'=>'icsoc_report_inallot',
        'trans_call'=>'icsoc_report_queueTranscall',
        'ragent'=>'icsoc_report_agent_home',
        'rqueue'=>'icsoc_report_queue_home',
        'rsystem'=>'icsoc_report_system_home',
        'evaluate'=>'icsoc_recording_list', //满意度满意报表-->录音管理；
        'collect'=>'icsoc_report_evaluatecollec',
        'agentcall'=>'icsoc_report_charts_agentcall',
        'queuecall'=>'icsoc_report_charts_queuecall',
        'evaluate_chart'=>'icsoc_report_charts_evaluate',
        'incoming_area'=>'icsoc_report_charts_inarea',
        'incoming_hour'=>'icsoc_report_charts_inhour',
        'caller_type'=>'icsoc_report_charts_calltype',
        'xtrz'=>'icsoc_log_index',
        'notice'=>'icsoc_notice_index',
        'configs'=>'icsoc_security_setting',
        'agent_add'=>'icsoc_agent_add',
        'agent_edit'=>'icsoc_agent_edit',
        'agent_del'=>'icsoc_agent_del',
        'queue_upload'=>'icsoc_queue_batch',
        'agentwork'=>'icsoc_report_charts_agentwork',
        'records_export'=>'icsoc_recording_list_batch_down_data',
        'mcalls'=>'icsoc_monitor_system_monitor', //排队监控
        'mqueue'=>'icsoc_monitor_system_monitor', //技能组监控
        'magent'=>'icsoc_monitor_system_monitor', //坐席监控
        'hangup_sms'=>'icsoc_security_setting', //参数设计，关机短信
        'agent_login'=>'icsoc_agent_login', //坐席切换,列表中的登陆
    );

    /** @var array 不需要转化的企业 */
    private $notTranVccCode = array(
        '1014091503'
    );

    protected function configure()
    {
        $this
            ->setName('role:transformation')
            ->setDescription('角色权限转化')
            ->addOption('vcc_code', null, InputOption::VALUE_REQUIRED, '企业代码')
            ->addOption('flag', null, InputOption::VALUE_OPTIONAL, '方向1(old=>new),2(new=>old)', 1);
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("start");
        $vccCode = $input->getOption('vcc_code');
        $flag = $input->getOption('flag');
//        if (empty($vccCode)) {
//            $output->writeln("vcc_code is not empty"); //保险不能都为空；
//            exit;
//        }
        $this->relation = $flag == 1 ? $this->relation : array_flip($this->relation);
        //cc_role转换；
        $this->processActionList('cc_roles', $vccCode);
        //ccods;
        $this->processActionList('cc_ccods', $vccCode);
        $output->writeln("ok");
        $output->writeln("end");
    }

    /**
     * @param $table
     * @param $vccCode
     */
    private function processActionList($table, $vccCode)
    {
        $conn = $this->getContainer()->get('doctrine.dbal.default_connection');
        $NoVccCode = "'".implode("','", $this->notTranVccCode)."'";
        if (!empty($vccCode)) {
            $codes = explode(',', $vccCode);
            $vccCodes = array();
            foreach ($codes as $vccCode) {
                $vccCodes[] = array('vcc_code'=>$vccCode);
            }
        } else {
            $vccCodes = $conn->fetchAll(
                "SELECT vcc_code FROM cc_ccods WHERE vcc_code NOT IN ($NoVccCode)"
            );
        }
        foreach ($vccCodes as $vccCode) {
            $vccCode = $vccCode['vcc_code'];
            $vccId = $conn->fetchColumn("SELECT vcc_id FROM cc_ccods WHERE vcc_code = '{$vccCode}'");
            $where = " vcc_id =  '{$vccId}' ";
            //查询是否开启白名单；
            $vccConfig = $conn->fetchAssoc("SELECT is_enable_white FROM cc_ccod_configs WHERE ".$where);
            //开启所有的黑名单；
            $conn->update(
                'cc_ccod_configs',
                array('is_enable_black'=>1,'is_incoming_enable_black'=>1),
                array('vcc_id'=>$vccId)
            );
            $roleId = $table == 'cc_roles' ? ',role_id ' : '';
            $list = $conn->fetchAll("SELECT action_list,vcc_id $roleId FROM {$table} WHERE ".$where);
            foreach ($list as $row) {
                $actions = array_filter(explode(',', $row['action_list']));
                $new = array();
                foreach ($actions as $val) {
                    if ($val == 'blacklist' ||
                        (isset($vccConfig['is_enable_white']) && $vccConfig['is_enable_white'] == 1)) {
                        $new[] = 'icsoc_security_setting'; //黑名单权限给参数设置权限；开启白名单也给参数设置权限；
                    }
                    $new[] = isset($this->relation[$val]) ? $this->relation[$val] : $val;
                }
                //如果开启了白名单就设置给ccods 设置权限；
                if (isset($vccConfig['is_enable_white'])
                    && $vccConfig['is_enable_white'] == 1 && $table == 'cc_ccods') {
                    $new[] = 'icsoc_namelist_white_index';
                }
                $newAction = array_unique(array_merge($new, $actions)); //去掉重复
                $newStr = implode(',', $newAction);
                //加上记录日志
                $logFile = "/var/log/manage/".$table.'_'.date('Y-m-d').".txt";
                $logId =  $table == 'cc_roles' ? $row['role_id'] : $row['vcc_id'];//记录日志id
                file_put_contents(
                    $logFile,
                    $logId.'-----------'.$row['action_list'].'===>'.$newStr."\r\n",
                    FILE_APPEND
                );
                $whereId = $table == 'cc_roles' ? " AND role_id = {$row['role_id']} " : '';
                $conn->executeQuery("UPDATE {$table} SET action_list = '{$newStr}' WHERE ".$where.$whereId);
            }
        }
    }
}
